﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Threading;
using Dapper;
using DotnetSpider.Http;
using Newtonsoft.Json.Linq;
 

namespace DotnetSpider.Agent
{
    public static class TokenHelper
	{

		public static void UpdateRequest(Request request, SpiderOptions Options_)
		{
			try
			{
				string user = Options_.user;
				if (!request.RequestUri.AbsoluteUri.Contains("faxin"))
				{
					return;
				}

				//DataTable dt = new DataTable();
				//using (var conn = new SqlConnection(Options_.StorageConnectionString))
				//{
				//	dt = DataTableToIDataReader(conn.ExecuteReader($"select * from LawOptions where id = '"+ user + "' "));
				//}

				//request.SetHeader("authorization", AlphaSpider.authorization);
				//request.Cookie = AlphaSpider.cookie;
				//request.SetHeader("token", AlphaSpider.token);

				if (request.Headers.ContainsKey("Cookie"))
				{
					request.Headers["Cookie"] = request.Headers["Cookie"] + ";" + Options_.cookies;//dt.Rows[0]["cookie"].ToString();
				}
				else
				{
					request.Headers.Add("Cookie", Options_.cookies);//dt.Rows[0]["cookie"].ToString());
				}

				if (request.Headers.ContainsKey("Content-Type"))
				{
					request.Headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
				}
				else
				{
					request.Headers.Add("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
				}
			}
			catch (Exception ex)
			{
				//Log.Logger.Error(ex.ToString());
			}



		}

		public static DataTable DataTableToIDataReader(IDataReader reader)
		{
			DataTable objDataTable = new DataTable("Table");
			int intFieldCount = reader.FieldCount;
			for (int intCounter = 0; intCounter < intFieldCount; ++intCounter)
			{
				objDataTable.Columns.Add(reader.GetName(intCounter).ToUpper(), reader.GetFieldType(intCounter));
			}
			objDataTable.BeginLoadData();
			object[] objValues = new object[intFieldCount];
			while (reader.Read())
			{
				reader.GetValues(objValues);
				objDataTable.LoadDataRow(objValues, true);
			}
			reader.Close();
			objDataTable.EndLoadData();
			return objDataTable;
		}


	}
}
